<template>
	<el-dialog :title="titleMap[mode]" v-model="visible"  destroy-on-close @closed="$emit('closed')" :close-on-click-modal="false" :close-on-press-escape="mode != 'show' ? false : true" fullscreen>
		<el-form :model="form" :rules="rules" :disabled="mode=='show'" label-width="120" ref="dialogForm" style="height:750px;overflow:auto;overflow-x:hidden;">
            <el-row :gutter="1">
                <el-col :span="6">
                    <el-form-item label="关联销售单" prop="contract_id">
                        <div style="display:flex;width:100%">
                            <el-input v-model="contract_code" placeholder="请选择销售单" readonly @click="checkContract"></el-input>
                            <el-button type="info" icon="el-icon-Close" @click="clearProduct"></el-button>
                        </div>
                    </el-form-item>
                </el-col>
                <el-col :span="6">
					<el-form-item label="关联采购出库单" prop="send_id">
						<div style="display:flex;width:100%">
							<el-input v-model="send_code" placeholder="请选择采购出库单" readonly @click="checkOut"></el-input>
							<el-button type="info" icon="el-icon-Close" @click="clearOut"></el-button>
						</div>
					</el-form-item>
				</el-col>
                <el-col :span="6">
                    <el-form-item label="客户" prop="customer_id">
                        <el-select v-model="form.customer_id" placeholder="请选择" filterable :disabled="form.contract_id != ''">
                        <el-option v-for="item in clientList" :key="item.id" :label="item.customer_name" :value="item.id"></el-option>
                    </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item label="采购单号" prop="return_code">
                        <el-input v-model="form.return_code" placeholder="请输入采购单号" clearable></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item label="退货日期" prop="open_date">
                        <el-date-picker v-model="form.open_date" type="date" placeholder="请选择日期" :value-format="'YYYY-MM-DD'" style="width:100%" />
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item label="退货仓库" prop="ware_id">
                        <el-select v-model="ware_id" filterable style="width: 100%" placeholder="请选择仓库" @change="wareChange" clearable>
                            <el-option v-for="item in wareList" :key="item.id" :label="item.ware_name" :value="item.id" />
                        </el-select>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row :gutter="1">
                <el-col :span="12">
                    <el-form-item label="备注" prop="remark">
                        <el-input v-model="form.remark" placeholder="请输入备注" type="textarea" clearable></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                     <el-form-item label="附件" prop="enclosure">
                        <sc-upload-file v-model="form.enclosure" :is_same_name="1">
                            <el-button type="primary" icon="el-icon-upload">选择文件</el-button>
                        </sc-upload-file>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-form-item label="退货清单" prop="detail">
                <el-button type="primary" size="small" icon="el-icon-plus" @click="checkGoods" v-if="form.contract_id == ''">选择商品</el-button>
                <sc-form-table ref="table" v-model="form.detail" :addTemplate="addTemplate" placeholder="暂无数据" height="400" hideAdd :hideDelete="form.contract_id != '' || form.send_id != ''" show-summary>
                    <el-table-column label="商品名称" align="center">
                        <template #default="scope">
                            {{scope.row.goods_name}}
                        </template>
                    </el-table-column>
                    <el-table-column label="商品编码" align="center">
                        <template #default="scope">
                            {{scope.row.goods_code}}
                        </template>
                    </el-table-column>
					<el-table-column label="商品图片" align="center">
						<template #default="scope">
							<el-image v-if="scope.row.goods_image" style="width: 30px; height: 30px; border-radius: 5px;" :src="scope.row.goods_image" :preview-src-list="[scope.row.goods_image]" preview-teleported="true" hide-on-click-modal align="center"></el-image>
						</template>
					</el-table-column>
                    <el-table-column label="规格型号" align="center">
                        <template #default="scope">
                            {{scope.row.goods_spec}}
                        </template>
                    </el-table-column>
                    <el-table-column label="分类" align="center">
                        <template #default="scope">
                            {{scope.row.cate_name}}
                        </template>
                    </el-table-column>
                    <el-table-column label="单位" align="center">
                        <template #default="scope">
                            {{scope.row.unit_name}}
                        </template>
                    </el-table-column>
                    <el-table-column label="数量" prop="number" align="center">
                        <template #default="scope">
                            <el-input v-model="scope.row.number" placeholder="数量" @input="totalCompute" @focus="onFocus($event)"></el-input>
                        </template>
                    </el-table-column>
                    <el-table-column label="未税单价" align="center">
                        <template #default="scope">
                            <el-input v-model="scope.row.price" placeholder="未税单价" @input="totalCompute" @focus="onFocus($event)"></el-input>
                        </template>
                    </el-table-column>
                    <el-table-column label="含税单价" align="center">
                        <template #default="scope">
                            <el-input v-model="scope.row.tax_price" placeholder="含税单价" @input="taxCompute" @focus="onFocus($event)"></el-input>
                        </template>
                    </el-table-column>
                    <el-table-column label="税率" align="center">
                        <template #default="scope">
                            <el-input v-model="scope.row.tax_rate" placeholder="税率" @input="taxChange" @focus="onFocus($event)"></el-input>
                        </template>
                    </el-table-column>
                    <el-table-column label="税额" align="center">
                        <template #default="scope">
                            {{ scope.row.tax_rate && scope.row.price && scope.row.number ?
                            (((1 + (Number(scope.row.tax_rate) / 100)) * Number(scope.row.price)* Number(scope.row.number)) - ((Number(scope.row.price) * Number(scope.row.number)))).toFixed(2) : 0 }}
                        </template>
                    </el-table-column>
                    <el-table-column label="未税合计" prop="amount" align="center"></el-table-column>
                    <el-table-column label="含税合计" prop="total_price" align="center"></el-table-column>
                    <el-table-column label="退货仓库" align="center">
                        <template #default="scope">
                            <el-select v-model="scope.row.ware_id" filterable style="width: 100%" placeholder="仓库">
                                <el-option v-for="item in wareList" :key="item.id" :label="item.ware_name" :value="item.id" />
                            </el-select>
                        </template>
                    </el-table-column>
                </sc-form-table>
            </el-form-item>
            <el-row :gutter="1">
                <el-col :span="6">
					<el-form-item label="实退金额" prop="pay_money">
						<el-input v-model="form.pay_money" placeholder="实退金额" clearable @input="payInput"></el-input>
					</el-form-item>
				</el-col>
                <el-col :span="6">
					<el-form-item label="结算账户" prop="settlement_id">
						<el-select v-model="form.settlement_id" filterable clearable placeholder="请选择账户" style="width:100%">
							<el-option v-for="item in accountList" :key="item.id" :label="item.account" :value="item.id"/>
						</el-select>
					</el-form-item>
				</el-col>
				<el-col :span="6">
					<el-form-item label="本次退款" prop="cost_money">
						<el-input v-model="form.cost_money" placeholder="本次退款" clearable @input="costInput"></el-input>
					</el-form-item>
				</el-col>
			</el-row>
		</el-form>
        <el-footer style="text-align: right;position: fixed;bottom: 0;right: 0;left: 0;padding: 10px 20px;background: #fff;border-top: 1px solid #eee;">
			<el-button @click="visible=false" >取 消</el-button>
			<el-button v-if="mode!='show'" type="primary" :loading="isSaveing" @click="submit(0)">保存</el-button>
			<el-button v-if="mode == 'add'" type="primary" :loading="isSaveing" @click="submit(1)">保存并审核</el-button>
		</el-footer>
	</el-dialog>
    <select-contract v-if="dialog.save" ref="saveDialog" @success="contractUpdate" @closed="dialog.save=false" :query="{status:1}"></select-contract>
    <select-goods v-if="dialog.goods" ref="goodsDialog" @success="goodsUpdate" @closed="dialog.goods=false" :query="{system_disable:0}"></select-goods>
    <select-out v-if="dialog.out" ref="outDialog" @success="outUpdate" @closed="dialog.out=false" :query="{system_disable:0}"></select-out>
</template>

<script>
import selectContract from '../contract/selectContract.vue';
import selectGoods from '../../goods/info/selectGoods.vue';
import SelectOut from '../out/selectOut.vue';
	export default {
    components: { selectContract, selectGoods, SelectOut },
		emits: ['success', 'closed'],
		data() {
			return {
				mode: "add",
				titleMap: {
					add: '新增销售退货单',
					edit: '编辑销售退货单',
					show: '查看销售退货单',
				},
				visible: false,
				isSaveing: false,
				form: {
					id:"",
                    contract_id: "",
                    send_id: "",
                    customer_id: "",
					return_code: "",
					open_date: this.moment().format('YYYY-MM-DD'),
					remark: "",
					enclosure: "",
                    detail:[],
                    is_check: 0,
                    settlement_id: "",
                    pay_money: "",
                    cost_money: "",
				},
                addTemplate:{},
                dialog: {
                    save: false,
                    goods: false,
                    out: false,
                },
                wareList:[],
                contract_code: "",
                send_code: "",
                ware_id: "",
                clientList:[],
                taxObj: {},
			    accountList: [],
			}
		},
		mounted() {
            this.getWare()
            this.getGetCode()
            this.getClient()
		    this.getAccount() // 账号
            this.getIsTax()
		},
		methods: {
			//显示
			open(mode='add'){
				this.mode = mode;
				this.visible = true;
				return this
			},
			//表单提交方法
			submit(e){
                this.form.is_check = e
                this.$refs.dialogForm.validate(async (valid) => {
                    if (valid) {
                        this.isSaveing = true;
                        var res  = [];
                        if (this.form.id) {
                            res = await this.$API.procure.contractreturn.edit.post(this.form);
                        }else{
                            res = await this.$API.procure.contractreturn.add.post(this.form);
                        }
                        this.isSaveing = false;
                        if(res!=''){
                            if(res.code == 1){
                                this.visible = false;
                                this.$emit('success', this.form, this.mode)
                                this.$message.success("操作成功")
                            }else{
                                this.$alert(res.message, "提示", {type: 'error'})
                            }
                        }
                    }
                })
			},
			//表单注入数据
			async setData(data){
				this.form.id = data.id
                var res = await this.$API.procure.contractreturn.detail.get({id:data.id});
                this.form.contract_id = res.data.contract_id
                this.contract_code = data.contract&&data.contract.contract_code
                this.form.send_id = res.data.send_id
                this.send_code = data.send_code
                this.form.remark = res.data.remark
                this.form.enclosure = res.data.enclosure
				this.form.customer_id = res.data.customer_id
			    this.form.settlement_id = res.data.settlement_id
			    this.form.pay_money = res.data.pay_money
			    this.form.cost_money = res.data.cost_money
                let array = []
                res.data.detail.map(item=>{
                    array.push({
                        id:item.id,
                        sales_detail_id: item.sales_detail_id,
                        goods_id:item.goods_id,
                        goods_name:item.goods && item.goods.goods_name,
                        unit_name:item.goods && item.goods.unit && item.goods.unit.unit_name,
                        cate_name:item.goods && item.goods.cate && item.goods.cate.cate_name,
                        goods_code:item.goods && item.goods.goods_code,
                        goods_spec:item.goods && item.goods.goods_spec,
                        goods_image:item.goods && item.goods.goods_image,
                        number:item.number,
                        price: item.price,
                        amount: (Number(item.number) * Number(item.price)).toFixed(2),
                        tax_price: item.tax_price,
                        total_price: item.total_price,
                        tax_rate: item.tax_rate,
                        ware_id:item.ware_id,
                    })
                })
                this.form.detail = array
			},
            checkContract(){
                this.dialog.save = true
                this.$nextTick(() => {
                    this.$refs.saveDialog.open('add')
                })
            },
            async contractUpdate(data){
                this.form.send_id = ""
                this.send_code = ""
                this.form.contract_id = data.id
                var res = await this.$API.contract.contract.detail.get({id: data.id});
                this.form.customer_id = res.data.customer_id
                this.contract_code = res.data.contract_code
                let array = []
                res.data.order_detail.map((item)=>{
                    array.push({
                        sales_detail_id: item.id,
                        goods_id: item.goods_id,
                        remark: item.remark,
                        goods_name: item.goods && item.goods.goods_name,
						goods_image: item.goods && item.goods.goods_image,
                        unit_name: item.goods && item.goods.unit && item.goods.unit.unit_name,
                        cate_name: item.goods && item.goods.cate && item.goods.cate.cate_name,
                        goods_code: item.goods && item.goods.goods_code,
                        goods_spec:item.goods && item.goods.goods_spec,
                        number: item.sale_num,
                        price: item.price,
                        amount: (Number(item.sale_num) * Number(item.price)).toFixed(2),
                        tax_price: item.tax_price,
                        total_price: item.total_price,
                        tax_rate: item.tax_rate,
                        ware_id:this.ware_id?this.ware_id:'',
                    })
                })
                this.form.detail = array
                this.totalCompute()
            },
            clearProduct(){
                this.form.contract_id = ""
                this.form.customer_id = ""
                this.contract_code = ""
                this.form.detail = []
            },
            checkOut(){
                this.dialog.out = true
                this.$nextTick(() => {
                    this.$refs.outDialog.open('add')
                })
            },
            async outUpdate(data){
                this.form.contract_id = ""
                this.form.customer_id = ""
                this.contract_code = ""
                this.form.send_id = data.id
                this.send_code = data.out_code
                var res = await this.$API.procure.contract.detail.get({id:data.id});
                let array = []
                res.data.detail.map(item=>{
                    array.push({
                        id:item.id,
                        sales_detail_id: item.sales_detail_id,
                        goods_id:item.goods_id,
                        goods_name:item.goods && item.goods.goods_name,
                        unit_name:item.goods && item.goods.unit && item.goods.unit.unit_name,
					    cate_name: item.goods && item.goods.cate && item.goods.cate.cate_name,
                        goods_code:item.goods && item.goods.goods_code,
					    goods_spec: item.goods && item.goods.goods_spec,
						goods_image: item.goods && item.goods.goods_image,
                        number:item.number,
                        tax_rate: this.taxObj.number,
                        amount: (Number(item.number) * Number(item.price)).toFixed(2),
                        tax_price: item.tax_price,
                        total_price: item.total_price,
                        price:item.goods && item.goods.factory_price,
                        remark:item.remark,
                        ware_id:item.ware_id,
                    })
                })
                this.form.detail = array
                this.totalCompute()
            },
            clearOut(){
                this.form.send_id = ""
                this.form.customer_id = ""
                this.send_code = ""
                this.form.detail = []
            },
            // 选择商品
            checkGoods(){
                this.dialog.goods = true
                this.$nextTick(() => {
                    this.$refs.goodsDialog.open('add')
                })
            },
            // 选择商品返回
            goodsUpdate(data){
                let array = []
                data.map((item)=>{
                    array.push({
                        goods_id:item.id,
                        goods_name:item.goods_name,
                        unit_name:item.unit && item.unit.unit_name,
                        cate_name:item.cate && item.cate.cate_name,
                        goods_code:item.goods_code,
                        goods_spec:item.goods_spec,
						goods_image:item.goods_image,
                        number: 1,
					    price: item.factory_price,
                        tax_rate: this.taxObj.number,
                        ware_id:this.ware_id?this.ware_id:'',
                    })
                })
                let existingIds = this.form.detail.map(item => item.goods_id);
                for(let i = array.length - 1; i >= 0; i--){
                    if(existingIds.includes(array[i].goods_id)){
                        array.splice(i, 1);
                    }
                }
                this.form.detail = [...this.form.detail,...array]
                this.totalCompute()
            },
            async getGetCode(){
                var res = await this.$API.procure.contractreturn.code.get();
                this.form.return_code = res.data.code
            },
            // 账户
            async getAccount() {
                var res = await this.$API.finance.account.all.get();
                this.accountList = res.data;
            },
            async getIsTax() {
                var res = await this.$API.setting.getSaleTax.get();
                this.taxObj = res.data
            },
            // 客户列表
            async getClient(){
                var res = await this.$API.client.client.all.get();
                this.clientList = res.data
            },
            // 获取仓库
            async getWare(){
                var res = await this.$API.goods.ware.all.get();
                this.wareList = res.data;
                if(this.mode == 'add'){
                    res.data.map(item=>{
                        if(item.is_default == 1){
                            this.ware_id = item.id
                        }
                    })
                }
            },
            async getLocationList(row){
                const res = await this.$API.goods.ware.position.post({ware_id:row.ware_id})
                row.locationList = res.data
            },
            onFocus(event){
                event.target.select();
            },
            wareChange(e){
                this.form.detail.map(item => item.ware_id = e)
            },
            /**计算总金额*/
            totalCompute() {
                let count_price = 0
                this.form.pay_money = 0
                this.form.detail.map(item => {
                    if (item.price && item.number) {
                        item.amount = (Number(item.number) * Number(item.price)).toFixed(2)
                        item.total_price = (Number(item.number) * Number(item.price) * (1 + (Number(item.tax_rate) / 100))).toFixed(2)
                        item.tax_price = ((1 + (Number(item.tax_rate) / 100)) * Number(item.price)).toFixed(2)
                        count_price = Number(count_price) + Number(item.total_price)
                    }
                })
                this.form.pay_money = count_price.toFixed(2)
                this.form.cost_money = this.form.pay_money
            },
            taxCompute(){
                let count_price = 0
                this.form.pay_money = 0
                this.form.detail.map(item => {
                    if (item.price && item.number) {
                        item.price = (item.tax_price / (1 + (Number(item.tax_rate) / 100))).toFixed(2)
                        item.amount = (Number(item.number) * Number(item.price)).toFixed(2)
                        item.total_price = (Number(item.number) * Number(item.tax_price)).toFixed(2)
                        count_price = Number(count_price) + Number(item.total_price)
                    }
                })
                this.form.pay_money = count_price.toFixed(2)
                this.form.cost_money = this.form.pay_money
            },
            taxChange(){
                let count_price = 0
                this.form.pay_money = 0
                this.form.detail.map(item => {
                    if (item.price && item.number) {
                        item.tax_price = ((1 + (Number(item.tax_rate) / 100)) * Number(item.price)).toFixed(2)
                        item.amount = (Number(item.number) * Number(item.price)).toFixed(2)
                        item.total_price = (Number(item.number) * Number(item.price) * (1 + (Number(item.tax_rate) / 100))).toFixed(2)
                        count_price = Number(count_price) + Number(item.total_price)
                    }
                })
                this.form.pay_money = count_price.toFixed(2)
                this.form.cost_money = this.form.pay_money
            },
            payInput(e){
                this.form.cost_money = e
            },
            costInput(e){
                if( e > Number(this.form.pay_money)){
                    this.$message.error('本次退款金额不能大于实退金额')
                    this.form.cost_money = this.form.pay_money
                }
            },
		}
	}
</script>

<style>
</style>
